const express = require('express')
const api = express.Router()
const db = require('../libs/DBhelper')
const jwt = require('jwt-simple') //制作token
const axios = require('axios')
const md5 = require('md5')
const alipaySdk = require('../libs/alipay')
const AlipayFormData = require('alipay-sdk/lib/form').default
api.post('/payment', (req, res) => {
    //   let orderId = req.body.orderId
    let orderId = Math.random().toString(36).substr(2)
    let sum = req.body.sum
    try {
        let params = [
            orderId,
            sum,
            req.body.address,
            req.body.phone,
            req.body.goods,
            req.body.email,
            Date.now()
        ]
        let sql =
            'insert into `orders` (`orderId`,`sum`,`address`,`phone`,`goods`,`email`,`datetime`) values(?,?,?,?,?,?,?)'
        db.exec(sql, params)
    } catch (error) {
        return res.json({ msg: '插入订单失败', code: -1 })
    }
    const formData = new AlipayFormData() // 创建表单对象
    formData.setMethod('get') // 支付宝支付接口
    formData.addField('return_url', 'http://localhost:8080/#/success') // 回调地址
    formData.addField('bizContent', {
        outTradeNo: orderId, // 订单号
        productCode: 'FAST_INSTANT_TRADE_PAY', // 支付宝支付接口
        totalAmount: sum, // 支付金额
        subject: '穗穗网', // 支付标题
        body: '在穗穗网购买商品', // 支付描述
    })
    const result = alipaySdk.exec(
        // 调用支付宝支付接口
        'alipay.trade.page.pay',
        {},
        { formData: formData },
    )
    result.then((resp) => {
        res.send({
            success: true,
            code: 1,
            payUrl: resp,
        })
    })
})

api.post('/getresult', async (req, res) => {
    const { out_trade_no, trade_no } = req.body
    //根据订单号查询金额
    const sql = 'SELECT SUM FROM `orders` WHERE orderId = ?'
    const sqlres = await db.exec(sql, [out_trade_no])
    //对接支付宝
    const formData = new AlipayFormData()
    formData.setMethod('get')
    formData.addField('bizContent', {
        out_trade_no,
        trade_no,
    })
    const result = alipaySdk.exec(
        // 调用支付宝支付接口
        'alipay.trade.query',
        {},
        { formData: formData },
    )
    result.then((resData) => {
        axios
            .get(resData)
            .then((data) => {
                let r = data.data.alipay_trade_query_response
                if (r.code === '10000') {
                    switch (r.trade_status) {
                        case 'WAIT_BUYER_PAY':
                            res.send({
                                success: true,
                                message: 'success',
                                code: 200,
                                timestamp: new Date().getTime(),
                                result: {
                                    status: 0,
                                    massage: '交易创建，等待买家付款',
                                },
                            })
                            break
                        case 'TRADE_CLOSED':
                            res.send({
                                success: true,
                                message: 'success',
                                code: 200,
                                timestamp: new Date().getTime(),
                                result: {
                                    status: 1,
                                    massage: '未付款交易超时关闭，或支付完成后全额退款',
                                },
                            })
                            break
                        case 'TRADE_SUCCESS':
                            res.send({
                                success: true,
                                message: 'success',
                                code: 200,
                                timestamp: new Date().getTime(),
                                result: {
                                    status: 2,
                                    massage: '交易支付成功',
                                    sum: sqlres[0].SUM
                                },
                            })
                            break
                        case 'TRADE_FINISHED':
                            res.send({
                                success: true,
                                message: 'success',
                                code: 200,
                                timestamp: new Date().getTime(),
                                result: {
                                    status: 3,
                                    massage: '交易结束，不可退款',
                                },
                            })
                            break
                    }
                } else if (r.code === '40004') {
                    res.send({ code: -1, msg: '订单不存在' })
                }
            })
            .catch((err) => {
                res.send({
                    success: false,
                    code: 0,
                    msg: '查询失败',
                    err,
                })
            })
    })
})

//登录接口
api.post('/login', async (req, res) => {
    let sql =
        'select *  from `users` where `email`=? and `pwd` =? and `status`=1 and power = 1'
    let params = [req.body.name, req.body.pwd]
    const result = await db.exec(sql, params)
    const status = result && result.length >= 1
    if (status) {
        const token = jwt.encode(result[0], 'hongs', 'HS256')
        res.json({ msg: '登录成功', code: 1, data: result[0], token })
    } else {
        res.json({ msg: '登录失败', code: -1 })
    }
})

//根据页数和条数获取用户信息
api.get('/getUserList', async (req, res) => {
    let page = req.query.page
    let limit = req.query.limit
    if (page && limit) {
        page = parseInt(page)
        limit = parseInt(limit)
    } else {
        return res.json({ msg: '请求的参数不对', code: -1 })
    }
    let sql = 'select * from `users` limit ?,?'
    let params = [(page - 1) * limit, limit]
    const result = await db.exec(sql, params)
    const status = result && result.length >= 1
    if (status) {
        const total = await db.exec('select count(*) as total from `users`')
        res.json({ msg: '获取成功', code: 1, data: result, total })
    } else {
        res.json({ msg: '获取失败', code: -1 })
    }
})

//根据名字查询用户信息
api.get('/getUserByEmail', async (req, res) => {
    let sql = 'select * from `users` where `email` like ? LIMIT ?,?'
    let page = parseInt(req.query.page)
      let limit = parseInt(req.query.limit)
    let params = [`%${req.query.email}%`, (page - 1) * limit, limit]
    const result = await db.exec(sql, params)
    const status = result && result.length >= 1
    if (status) {
        res.json({ msg: '获取成功', code: 1, data: result,total:result.length })
    } else {
        res.json({ msg: '获取失败', code: -1 })
    }
})



//根据id更新用户的状态
api.post('/updateUserStatus', async (req, res) => {
    let sql = 'update `users` set `status`=? where `id`=?'
    if (req.body.id == 6) {
        return res.json({ msg: '超级管理员不能修改', code: -1 })
    }
    let params = [req.body.status, req.body.id]
    const result = await db.exec(sql, params)
    const status = result && result.affectedRows >= 1
    if (status) {
        res.json({ msg: '更新成功', code: 1 })
    } else {
        res.json({ msg: '更新失败', code: -1 })
    }
})

// 添加用户
api.post('/addUser', async (req, res) => {
    let sql = 'insert into `users`(`email`,`pwd`,`img`,datatime) values(?,?,?,?)'
    let params = [req.body.email, md5(req.body.pwd), req.body.img, Date.now()]
    const result = await db.exec(sql, params)
    const status = result && result.affectedRows >= 1
    if (status) {
        res.json({ msg: '添加成功', code: 1 })
    } else {
        res.json({ msg: '添加失败', code: -1 })
    }
})

//根据id删除用户
api.post('/deleteUser', async (req, res) => {
    let sql = 'delete from `users` where `id`=?'
    if (req.body.id == 6) {
        return res.json({ msg: '超级管理员无法删除', code: -1 })
    }
    let params = [req.body.id]
    const result = await db.exec(sql, params)
    const status = result && result.affectedRows >= 1
    if (status) {
        res.json({ msg: '删除成功', code: 1 })
    } else {
        res.json({ msg: '删除失败', code: -1 })
    }
})

//根据id获取用户的头像和email
api.get('/getuserbyid', async function (request, response, next) {
    let sql = `SELECT id,email,img FROM users WHERE id =?`
    let params = [request.query.id]
    let result = await db.exec(sql, params)
    if (result && result.length > 0) {
        response.send({ code: 1, msg: '获取用户成功', data: result })
    } else {
        response.send({ code: 0, msg: '获取用户失败' })
    }
})

//更新用户的头像和email
api.post('/updateuser', async function (request, response, next) {
    let sql = `UPDATE users SET email = ?,img = ? WHERE id = ?`
    let params = [request.body.email, request.body.img, request.body.id]
    let result = await db.exec(sql, params)
    if (result && result.affectedRows > 0) {
        response.send({ code: 1, msg: '更新用户成功' })
    } else {
        response.send({ code: 0, msg: '更新用户失败' })
    }
})
//根据轮播图id清空指定的轮播图
api.post('/deleteimg', async function (request, response, next) {
  let sql = 'delete from `banner` where `id`=?'
  let params = [request.body.id]
  let result = await db.exec(sql, params)
  if (result && result.affectedRows > 0) {
    response.send({ code: 1, msg: '删除轮播图成功' })
  } else {
    response.send({ code: 0, msg: '删除轮播图失败' })
  }
})
// 添加轮播图
api.post('/addCarousel', async (req, res) => {
    let sql = 'insert into `banner`(bigimg,smlimg) values(?,?)'
    let params = [req.body.bigimg, req.body.smlimg]
    const result = await db.exec(sql, params)
    const status = result && result.affectedRows >= 1
    if (status) {
      res.json({ msg: '添加成功', code: 1 })
    } else {
      res.json({ msg: '添加失败', code: -1 })
    }
  })

  // 添加商品
api.post('/addGoods', async (req, res) => {
    let sql =
      'insert into `goods`(`brand`,`name`,`desc`,`price`,`img`,`showimg`,`gid`,`bid`) values(?,?,?,?,?,?,?,?)'
    let params = [
      req.body.brand,
      req.body.name,
      req.body.desc,
      req.body.price,
      req.body.img,
      req.body.showimg,
      req.body.gid,
      req.body.bid,
    ]
    const result = await db.exec(sql, params)
    const status = result && result.affectedRows >= 1
    if (status) {
      res.json({ msg: '添加成功', code: 1 })
    } else {
      res.json({ msg: '添加失败', code: -1 })
    }
  })
  
  // 获取所有订单信息
  api.get('/getAllOrder', async (req, res) => {
    let page = req.query.page
    let limit = req.query.limit
    if (page && limit) {
        page = parseInt(page)
        limit = parseInt(limit)
    } else {
        return res.json({ msg: '请求的参数不对', code: -1 })
    }
    let sql = 'select * from `orders` limit ?,?'
    let params = [(page - 1) * limit, limit]
    const result = await db.exec(sql, params)
    const status = result && result.length >= 1
    if (status) {
        const total = await db.exec('select count(*) as total from `orders`')
        res.json({ msg: '获取订单成功', code: 1, data: result, total })
    } else {
        res.json({ msg: '获取订单失败', code: -1 })
    }
})
  
// 删除商品接口
api.post('/deleteGoods', async (req, res) => {
    let sql = 'delete from `goods` where `id`=?'
    let params = [req.body.id]
    const result = await db.exec(sql, params)
    const status = result && result.affectedRows >= 1
    if (status) {
      res.json({ msg: '删除成功', code: 1 })
    } else {
      res.json({ msg: '删除失败', code: -1 })
    }
  })

  //根据邮箱和页数条数获取订单
api.get('/getOrderByEmail', async function (request, response, next) {
    //判断邮箱是否存在
    let sql = `SELECT email FROM users WHERE email = ?`
    let params = [request.query.email]
    let result = await db.exec(sql, params)
    if (result && result.length > 0) {
      //获取订单
      let sql = `SELECT * FROM orders WHERE email = ? LIMIT ?,?`
      let page = parseInt(request.query.page)
      let limit = parseInt(request.query.limit)
      let params = [request.query.email.toString(), (page - 1) * limit, limit]
      let result = await db.exec(sql, params)
      if (result && result.length > 0) {
        response.send({
          code: 1,
          msg: '获取订单成功',
          data: result,
          total: result.length,
        })
      } else {
        response.send({ code: 0, msg: '获取订单失败' })
      }
    } else {
      response.send({ code: 0, msg: '查询邮箱不存在' })
    }
  })

  //根据orderid获取更改订单状态
api.post('/updateOrderStatus', async (req, res) => {
    let sql = 'update `orders` set `status`=? where `orderId`=?'
    let params = [req.body.status, req.body.orderId]
    const result = await db.exec(sql, params)
    const status = result && result.affectedRows >= 1
    if (status) {
      res.json({ msg: '更改成功', code: 1 })
    } else {
      res.json({ msg: '更改失败', code: -1 })
    }
  })
module.exports = api
